<?php

use app\modules\Admin\models\upgradecodeModel;

use Illuminate\Database\Capsule\Manager as DB;
#[代理升级码管理]
class UpgradecodeController extends \AcommonController
{
    public function init() {
        $this->model = new upgradecodeModel();
        $this->table = 'upgrade_code';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[升级码列表]
    public function indexAction($returnData = FALSE)
    {
        if($this->isPost()){
            $this->model = $this->model->with(['relationMember', 'useMember']);
            $post_data = $this->postData;
            $search_data = [];
            if(isset($post_data['mode']) && !empty($post_data['mode']) && $post_data['mode'] != 'all'){
                array_push($search_data, ['status', '=', $post_data['mode']]);
            }
            if(isset($post_data['level']) && !empty($post_data['level'])){
                array_push($search_data, ['level', '=', $post_data['level']]);
            }
            if(isset($post_data['upgradecode_start']) && !empty($post_data['upgradecode_start'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['upgradecode_start']);
            }
            if(isset($post_data['upgradecode_end']) && !empty($post_data['upgradecode_end'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['upgradecode_end']);
            }
            $keywordsTypeArray = [
                'code_id' => 'code_id',
                'code_sn' => 'code_sn',
                'a_user_id' => 'a_user_id',
                'a_user_phone' => 'a_user_phone',
                'b_user_id' => 'b_user_id',
                'b_user_phone' => 'b_user_phone',
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                if($post_data['keywordsType'] == $keywordsTypeArray['code_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($search_data, ['id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['code_sn']){
                    array_push($search_data, ['code', 'like', "%{$post_data['keywords']}%"]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['a_user_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($search_data, ['member_id_relation', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['a_user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($search_data, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id_relation', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['b_user_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($search_data, ['member_id_use', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['b_user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($search_data, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id_use', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
            }
            unset($keywordsTypeArray);
            $this->search = $search_data;
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }else{
            $level_list = [];
            $levelModel = \agentlevelModel::query()->select('level', 'name')->orderBy('level', 'ASC')->get();
            if($levelModel){
                $level_list = $levelModel->toArray();
            }
            $this->_view->assign('level_list', json_encode($level_list, JSON_UNESCAPED_UNICODE));
            $this->_view->display( strtolower($this->controller) . '/index.html');
        }
    }

    #[生成升级码]
    public function addAction()
    {
        if (!$this->isPost()) {
            $level_list = [];
            $levelModel = \agentlevelModel::query()->select('level', 'name')->orderBy('level', 'ASC')->get();
            if($levelModel){
                $level_list = $levelModel->toArray();
            }
            $dataset = [
                'member_ids'=>[],
                'level'=>0,
                'number'=>0,
            ];
            $this->_view->assign('level_list', json_encode($level_list, JSON_UNESCAPED_UNICODE));
            $this->_view->assign('dataset', json_encode($dataset, JSON_UNESCAPED_UNICODE));
            $this->_view->display(strtolower($this->controller) . '/add.html');
        } else {
            $postData = $this->postData;
            if(!is_numeric($postData['level']) || empty($postData['level'])){
                ret(9, '升级码目标代理等级没有选择！');
            }
            if(!is_array($postData['member_ids']) || empty($postData['member_ids'])){
                ret(8,'没有选择持码客户');
            }
            if(!is_numeric($postData['number']) || empty($postData['number'])){
                ret(9, '没有填写发放的数量！');
            }
            $total_codes = intval($postData['number'])*count($postData['member_ids']);
            if($total_codes > 1000){
                ret(8,'单次生成数量太多，生成升级码失败');
            }
            $insert_data = [];
            $all_code = [];
            foreach ($postData['member_ids'] as $member_id){
                for ($i = 0; $i<$postData['number']; $i++){
                    $code = $this->createCode($all_code, 8);
                    array_push($all_code, $code);
                    $temp_data = [
                        'code'=>$code,
                        'level'=>$postData['level'],
                        'time_release'=>timestamp(),
                        'time_use'=>null,
                        'member_id_relation'=>$member_id,
                        'member_id_use'=>0,
                        'oper_type'=>'admin',
                        'oper_id'=> $this->auth->user_id,
                        'status'=>'unused',
                        'created_at'=>timestamp(),
                    ];
                    array_push($insert_data, $temp_data);
                }
                unset($i, $temp_data, $code);
            }
            unset($member_id);
            try {
                DB::transaction(function () use($insert_data){
                    upgradecodeModel::query()->insert($insert_data);
                });
                ret(0, '生成升级码成功！');
            }catch (Exception $e){
                ret(1, $e->getMessage());
            } finally {
                unset($insert_data, $all_code, $total_codes, $postData);
            }
        }
    }

    /**
     * @param array $all
     * @param int $length
     * @return string
     */
    private function createCode(array $all = [], int $length):string
    {
        $code = upgradecodeModel::createSn($length);
        if(in_array($code, $all)){
            $code = $this->createCode($all, $length);
        }
        return $code;
    }

    #[删除升级码]
    public function deleteAction()
    {
        $id = $this->get($this->primaryKey, []);
        if (empty($id)) {
            ret(9, '参数为空');
        }
        if (!is_numeric($id)) {
            ret(8, '参数格式出错');
        }
        $model = upgradecodeModel::query()->where($this->primaryKey, $id)->first();
        if(!$model){
            ret(7, '升级码不存在！');
        }
        if ($model->status !== 'disabed'){
            ret(6, '非禁用升级码不能删除！');
        }
        parent::deleteAction(); // TODO: Change the autogenerated stub
    }

    #[禁用升级码]
    public function disablecodeAction()
    {
        $id = $this->get($this->primaryKey, []);
        if (empty($id)) {
            ret(9, '参数为空');
        }
        if (!is_numeric($id)) {
            ret(8, '参数格式出错');
        }
        $model = upgradecodeModel::query()->where($this->primaryKey, $id)->first();
        if(!$model){
            ret(7, '升级码不存在！');
        }
        if ($model->status === 'used'){
            ret(6, '升级码已使用无法操作！');
        }
        if($model->status === 'unused'){
            $new_status = 'disabed';
            $status_opt_text = '禁用';
        }else{
            $new_status = 'unused';
            $status_opt_text = '启用';
        }
        $model->status = $new_status;
        $model->updated_at = timestamp();
        if($model->save()){
            ret(0, $status_opt_text.'升级码成功！');
        }else{
            ret(1, $status_opt_text.'升级码失败！');
        }
    }

    #[目标代理等级修改]
    public function levelAction()
    {
        $id    = $this->get('id');
        $level = $this->get('level');
        if ($this->isPost()) {
            try {
                $upgradecode = upgradecodeModel::where('id', $id)->first();
                if(!$upgradecode){
                    throw new Exception('升级码不存在', 3);
                }
                $levelModel = agentlevelModel::query()->where('level', $level)->first();
                if(!$levelModel){
                    throw new Exception('目标代理等级不存在', 1);
                }
                if($upgradecode->level == $level){
                    throw new Exception('目标代理等级未更改', 2);
                }
                DB::beginTransaction();
                $upgradecode->level = $level;
                $upgradecode->updated_at = timestamp();
                $upgradecode->save();
                DB::commit();
                $result = [
                    'ret' => 0,
                    'msg' => '操作成功',
                ];
            } catch (Exception $e) {
                DB::rollback();
                $result = [
                    'ret' => 30001,
                    'msg' => $e->getMessage(),
                ];
            }
            json($result);
        } else {
            $this->_view->assign('id', $id);
            $this->_view->assign('curr', $this->get('curr'));
            $this->_view->display(strtolower($this->controller) . '/level.html');
        }
    }

    #[获取可成为管理员的用户列表]
    public function getmemberlistAction()
    {
        if($this->isPost()){
            $type     = $this->get('keywordsType');
            $keywords = $this->get('keywords');
            $query = memberModel::query()->where('status', '=', 'normal')->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
            });
            if (!empty($keywords)) {
                switch ($type){
                    case 'id':
                        $query->where("id", $keywords);
                        break;
                    case 'nickname':
                        $query->where("nickname", 'like', "%{$keywords}%");
                        break;
                    case 'phone':
                        $query->where("phone", 'like', "%{$keywords}%");
                        break;
                }
            }
            $total = $query->count();
            $query = $query->select([
                "id",
                "avatar",
                "nickname",
                "phone",
            ]);
            $page = $this->get('page', 1);
            $limit = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $query = $query->offset($offset)->limit($limit);
            $rows = $query->orderByDesc('id')->get()->makeHidden(['nickname_hide'])->append('level_info');
            json(['total' => $total, 'rows' => $rows]);
        }else{
            $this->_view->display( strtolower($this->controller) . '/getmemberlist.html');
        }
    }
}